declare namespace pm = "http://www.politicalmashup.nl";

declare function local:generate_topic_titles_for_subjects() {
    let $topicIds := distinct-values( doc('/db/projdb/clusterdataSortedBySpeakers.xml')/speakers/speaker/clusters/cluster/label/topics/topic)
    let $sourceTopics := collection('/db/projdb/ge-2009')/root/pm:proceedings/pm:topic
    return <topics>
    {
    for $topicId in $topicIds 
        return 
            <topic id="{$topicId}">
                <title>{data($sourceTopics[@pm:id = $topicId]/@pm:title)}</title>
            </topic>
    } </topics>
};

    let $collection := 'xmldb:exist:///db/projdb'
    let $file-name := 'topic_titles_for_subjects.xml'

    let $store-return-status := xmldb:store($collection, $file-name, document{local:generate_topic_titles_for_subjects()} )

    return <message>New Document Created {$store-return-status} at {$collection}/{$file-name}</message>
